package com.nuo.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.nuo.common.exception.GlobalException;
import com.nuo.config.LocalYml;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;

@Component
public class FileUtils {

    @Resource
    LocalYml localYml;


    private static void uploadFile(byte[] file, String filePath, String fileName)throws Exception{
        File targetFile = new File(filePath);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        FileOutputStream out = new FileOutputStream(filePath+"/"+fileName);
        out.write(file);
        out.flush();
        out.close();
    }

    public  R  uploadFileByPathName(MultipartFile file, String pathName) {
        System.out.println(file);
        //实例化json数据
        JSONObject jo = new JSONObject();
        if(file==null){
            throw new GlobalException("文件为空，上传失败！");
        }
        String fileName = System.currentTimeMillis()+file.getOriginalFilename();
        String filePath = localYml.getUploadAddress()+"/"+pathName;
        try {
            uploadFile(file.getBytes(), filePath, fileName);
            jo.put("fileUrl", localYml.getVisitAddress()+pathName+"/"+fileName);
            jo.put("fileName", fileName);
        } catch (Exception e) {
            throw new GlobalException("文件上传失败");
        }
        //返回json
        return R.ok(jo);
    }
}
